//
//  HDShowMessageManager.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/8.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit

class HDShowMessageManager: NSObject {
    weak var messageView:MessageView?
    static let sharedManager: HDShowMessageManager = {
        let manager = HDShowMessageManager()
        return manager
    }()
    
    func showMessage(_ controller: UITableViewController,message: String,success: Bool){
        let flag:Bool = messageView == nil ? true : false
        let view = MessageView(onVC: controller,message: message, success: success)
        if self.messageView != nil{
            view.y = 64
        }
        self.messageView?.layer.removeAllAnimations()
        controller.tableView.layer.removeAllAnimations()
        HDShowMessageManager.cancelPreviousPerformRequests(withTarget: self, selector: #selector(HDShowMessageManager.messageAnimation(_ :)), object: self.messageView)
        self.messageView?.removeFromSuperview()
        self.messageView = nil
        controller.navigationController?.view.insertSubview(view, at: 1)
        UIView.animate(withDuration: 0.5, animations: {
            view.y = 64
        }) 
        if flag {
            UIView.animate(withDuration: 0.5, animations: {
                if controller.tableView.contentSize.height > KscreenHeight - controller.tableView.contentInset.top - controller.tableView.contentInset.bottom {
                    controller.tableView.contentInset.top = 64 + view.height
                    controller.tableView.contentOffset.y =  controller.tableView.contentOffset.y - view.height
                }else{
                    controller.tableView.contentInset.top = 64 + view.height
                }
            }) 
        }
        self.messageView = view
        self.perform(#selector(HDShowMessageManager.messageAnimation(_:)), with: view, afterDelay: 2.5)
    }
    
    func messageAnimation(_ View: MessageView){
        let vc = View.controller
        guard vc != nil else{
            return
        }
        UIView.animate(withDuration: 0.5, animations: {
            vc!.tableView.contentOffset.y = vc!.tableView.contentOffset.y + View.height
            vc!.tableView.contentInset.top = 64
            View.y = 24
        }, completion: { (true) in
            View.removeFromSuperview()
        }) 
    }

}
